<?php
/**
 * Created by ephp
 * User: 22071
 * Date: 2019/6/14
 * Email: <zhendongdong@foxmail.com>
 */

namespace paper\http;


use paper\App;

class Response
{
    private $code = 200;
    private $data;
    private $header = [];
    protected $contentType = 'text/html';
    private $app;


    private function __construct($data = '', $code = 200, array $header = [])
    {
        $this->data = $data;
        $this->code = $code;
        $this->app  = App::getInstance();
        $this->contentType($this->contentType);
        $this->header = array_merge($this->header, $header);
    }


    public static function create($data = '', $code = 200, $type = '', array $header = [])
    {
        if ($type) {
            $class = false !== strpos($type, '\\') ? $type : '\\paper\\response\\' . ucfirst(strtolower($type));
            if (class_exists($class)) {
                return new $class($data, $code, $header);
            }
        }
        return new self($data, $code, $header);
    }


    public function send()
    {
        http_response_code($this->code);
        foreach ($this->header as $key => $value) {
            header($key . (!is_null($value) ? ':' . $value : ''));
        }
        $data = $this->output($this->data);
        $this->sendData($data);
        $this->showDebug();

        if (function_exists('fastcgi_finish_request')) {
            // 提高页面响应
            fastcgi_finish_request();
        }

    }

    /**
     * 显示底部调试信息
     */
    private function showDebug()
    {
        if ($this->app->config->app('trace')) {
            $runTime = App::getInstance()->proEndTime();
            include PAPERPHP . '/library/tpl/log.php';
        }
    }

    /**
     * 页面输出类型
     * @access public
     * @param string $contentType 输出类型
     * @param string $charset 输出编码
     * @return Response
     */
    public function contentType($contentType, $charset = 'utf-8')
    {
        $this->header['Content-Type'] = $contentType . '; charset=' . $charset;
        return $this;
    }

    protected function sendData($data)
    {
        if ($data instanceof \Closure) {
            $data();
        } else {
            echo $data;
        }
    }

    protected function output($data)
    {
        return $data;
    }


}